import { ToastController, AlertController, Platform, App } from "ionic-angular";
import { PcSeriveProvider } from "./../../../providers/pc-serive/pc-serive";
import { Component, ViewChild } from "@angular/core";
import { IonicPage, NavController, NavParams, Navbar } from "ionic-angular";
import { BaseUI } from "../../../common/baseUI";

/**
 * Generated class for the PcSmItemPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: "page-pc-sm-item",
  templateUrl: "pc-sm-item.html"
})
export class PcSmItemPage extends BaseUI {
  @ViewChild(Navbar) navBar: Navbar;
  allEval = []; //显示列表
  teamImg; //;团队头像
  evalcode; //评测id
  evaluatingrule: string; //评测总分规则
  ifshow = [];
  max; //最大值
  min; //最小值
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private pcSerive: PcSeriveProvider,
    private toastCtrl: ToastController,
    private alertCtrl: AlertController,
  ) {
    super();
    this.teamImg = this.navParams.get("teamImg"); //团队头像
    this.evalcode = this.navParams.get("evaluatingCode"); //评测编号
  }

  //提交按钮
  submission() {
    this.pcSerive.getevalval(this.evalcode).subscribe(data => {



      if (data["status"] == 400) {
        this.showToast(this.toastCtrl, "评测内容未填完整");
      } else {
        //取出key和值做查找和判断
        let i = data["data"];
        let listdata = [];
        for (const key in i) {
          if (i.hasOwnProperty(key)) {
            let n = {
              usercode: key,
              value: i[key]
            };
            listdata.push(n);
          }
        }
        //按照分数排序
        listdata.sort(this.comparecompare("value"));
        //查询人名完毕之后选择最大和最小值
        this.maxMin(listdata);

        //判断是高低分差是否合格
        if (this.max['value'] - this.min['value'] < this.evaluatingrule['alldiff']) {
          super.alertShow(
            this.alertCtrl,
            `最大分 ${this.max['usercode']}${this.max['value']} 减
            最小分 ${this.min['usercode']}${this.min['value']}                  
            不能小于${this.evaluatingrule['alldiff']}`
          )
          return null;
        }
        //主要作用就是判断总分是否合格 
        let number = Math.floor(listdata.length / 2);//获取50%的列表

        setTimeout(() => {
          for (let id = 0; id < listdata.length - number; id++) {
            if (listdata[id]["value"] - listdata[id + number]["value"] < this.evaluatingrule['allsort']) {
              this.alertShow(
                this.alertCtrl,
                `${listdata[id]["usercode"]}${listdata[id]["value"]}总分减
                ${listdata[id + number]["usercode"]}${listdata[id + number]["value"]}总分
                不能小于${this.evaluatingrule['allsort']}`
              );
              return null;
            }
          }
          this.showToast(this.toastCtrl, '评测完成,评测报告将在结束后一天生成');
          localStorage.setItem('isback', '1');
          this.navCtrl.pop();
        }, 20);
      }
    });
  }

  //跳转输入分值界面
  openInput(id) {
    this.navCtrl.push("PcInputPage", {
      id: id, //选择的小项目id
      evalcode: this.evalcode, //评测id
      state: this.ifshow[id],
    });

  }

  //选择按照数组中的某个选项排序
  comparecompare(item) {
    return function (obj1, obj2) {
      let val1 = obj1[item];
      let val2 = obj2[item];
      if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
        val1 = Number(val1);
        val2 = Number(val2);
      }
      if (val1 < val2) {
        return 1;
      } else if (val1 > val2) {
        return -1;
      } else {
        return 0;
      }
    };
  }
  //算最大最小值
  maxMin(valuedata: Array<any>) {
    this.max = valuedata[0];
    this.min = valuedata[valuedata.length - 1];
  }


  //页面每次进入的时候都要更新下填没填
  ionViewDidEnter() {

    this.pcSerive.getSmEvalList(this.evalcode).subscribe(data => {

      let leng = JSON.parse(data["evaluating"]["evaluatingproject"]); //获取单项的列表
      this.evaluatingrule = data["evaluating"]["evaluatingrule"]; //获取总分规则
      this.evaluatingrule = JSON.parse(this.evaluatingrule.replace(/\'/g, '"'));

      this.allEval = [];//每次进来都要初始化，不然会叠加数据
      for (let i = 0; i < leng.length; i++) {
        this.allEval.push(leng[i]);
        if (i == leng.length - 1) {
          for (let n = 0; n < data['booleans'].length; n++) {
            this.ifshow[n] = data['booleans'][n];
          }
        }
      }
    });
  }


  //更改界面左上角的返回触发的操作
  ionViewDidLoad() {
    this.navBar.backButtonClick = this.backButtonClick;
  }
  backButtonClick = (e: UIEvent) => {
    let tf = 0;
    for (let index = 0; index < this.ifshow.length; index++) {
      if (this.ifshow[index] == true) {
        tf++;
      }
    }
    if (tf < this.ifshow.length) {
      super.showToast(this.toastCtrl, '评测未完成');
      this.navCtrl.pop();
    } else {
      super.showToast(this.toastCtrl, '评测完成,评测报告将在结束后一天生成');
      this.navCtrl.pop();
    }
  }

}
